package com.neoCalf.neoUser.webSocket.handler;

import com.neoCalf.neoUser.webSocket.tool.ChannelContextUtils;
import com.neoCalf.neoUser.webSocket.tool.WsDataTool;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@ChannelHandler.Sharable
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(HandlerWebSocket.class);
    @Resource
    private WsDataTool dataTool;
    @Resource
    ChannelContextUtils channelContextUtils;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String token = dataTool.decodeParamToString(complete, "token");
            if (token == null || token.isEmpty()) {
                ctx.writeAndFlush(new TextWebSocketFrame("token is empty"));
                ctx.close();
            }
            try {
                String userId = (String) dataTool.getValueByToken(token, "userId");
                dataTool.saveUserHeartBeat(userId);
                channelContextUtils.addContact(userId, token, ctx);
            } catch (Exception e) {
                ctx.close();
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        channelContextUtils.removeContext(incoming);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel incoming = ctx.channel();
        channelContextUtils.removeContext(incoming);
        logger.error(cause.getMessage());
    }
}
